package org.czkt.excel;

import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

public class ReadExcelUtil<T> {

    //1、工作薄workbook
    //2、工作表 sheet
    //3、row
    //4、cell


    public List<T> ReadExcel(File file, Class clazz) throws IOException, IllegalAccessException, InstantiationException {
        List<T> resultList = new ArrayList<>();

        Map<String, Integer> headerMap = new HashMap<>();

        //从文件中创建工作薄
        Workbook workbook = WorkbookFactory.create(file);


        //获取工作表
        Sheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.rowIterator();
        while (rowIterator.hasNext()) {
            Row tempRow = rowIterator.next();
            Iterator<Cell> cellIterator = tempRow.cellIterator();

            if (tempRow.getRowNum() > 0) {
                T t = (T) clazz.newInstance();

//                while (cellIterator.hasNext()) {
//                    Cell cell = cellIterator.next();

                Field[] fields = clazz.getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    if (headerMap.containsKey(fields[i].getName())) {
                        Cell cell = tempRow.getCell(headerMap.get(fields[i].getName()));

                        if (cell.getCellType() == CellType.STRING) {
//                            System.out.print(cell.getStringCellValue());
                            fields[i].setAccessible(true);
                            fields[i].set(t, cell.getStringCellValue());
                        }
                    }

//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            System.out.print(cell.getNumericCellValue());
//                        }
                }


//                }
                resultList.add(t);
            } else {
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (cell.getCellType() == CellType.STRING) {
                        headerMap.put(cell.getStringCellValue(), cell.getColumnIndex());

                    }
                }
            }
        }

        return resultList;


    }


    public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException {
        ReadExcelUtil<ProductEntity> readExcelUtil = new ReadExcelUtil<>();


        List<ProductEntity> productEntities = readExcelUtil.ReadExcel(new File("D:\\BaiduNetdiskDownload\\product_1715651661878.xlsx"), ProductEntity.class);
        for (int i = 0; i < productEntities.size(); i++) {
            System.out.println(productEntities.get(i).getProductName());
        }


    }


}
